
class EarlyStopping(object):
    def __init__(self, patience=7, max_better=True, delta=0,):
        self.patience = patience
        self.max_better = max_better  # more greater, more better
        self.counter = 0
        self.best_score = None
        self.early_stop = False
        self.delta = delta

    def __call__(self, val_metric):
        score = val_metric if self.max_better else -val_metric
        if self.best_score is None:
            self.best_score = score
            save_best_flag = True
        elif score < self.best_score + self.delta:
            self.counter += 1
            # print(f'EarlyStopping counter: {self.counter} out of {self.patience}')
            if self.counter >= self.patience:
                self.early_stop = True
            save_best_flag = False
        else:
            self.best_score = score
            self.counter = 0
            save_best_flag = True
        return save_best_flag

